import { defineStore } from "pinia";
import { reactive, ref } from "vue";
import { allItemsDatabase } from "@/config/items";
import type { IItem, IItemInstance, ItemQuality } from "@/type/item";

export interface InventorySlot {
  id: number; // 槽位ID
  item: IItemInstance | null; // 物品实例
  type: "hotbar" | "inventory"; // 槽位类型
}

export const useItemStore = defineStore("item", () => {
  const inventory = reactive<InventorySlot[]>([]); // 背包
  const selectedSlot = ref<number | null>(null); // 选中的物品槽位

  /**
   * 初始化背包
   * @param hotbarSize 快捷栏大小
   * @param inventorySize 背包大小
   */
  const initInventory = (hotbarSize: number, inventorySize: number) => {
    inventory.length = 0;

    for (let i = 0; i < hotbarSize; i++) {
      inventory.push({
        id: i,
        item: null,
        type: "hotbar",
      });
    }

    for (let i = 0; i < inventorySize; i++) {
      inventory.push({
        id: hotbarSize + i,
        item: null,
        type: "inventory",
      });
    }

    addItemToInventory("axe", 1);
    addItemToInventory("hoe", 1);
    addItemToInventory("decorative_bowl", 1);
    addItemToInventory("walnut_chair", 1);
    addItemToInventory("oak_table", 1);
  };

  /**
   * 获取物品实例
   * @param itemId 物品ID
   * @returns 物品实例
   */
  const getItemById = (itemId: string): IItem | undefined => {
    return allItemsDatabase[itemId];
  };

  /**
   * 添加物品到背包
   */
  const addItemToInventory = (
    itemId: string,
    count: number,
    quality?: ItemQuality
  ): boolean => {
    const itemData = getItemById(itemId);
    if (!itemData) return false;

    // 如果物品可堆叠，尝试合并到现有堆叠
    if (itemData.stackable && count > 0) {
      // 查找背包中已有的相同物品堆叠
    }

    // 查找背包中的空位
    const emptySlot = inventory.find((slot) => slot.item === null);
    if (!emptySlot) return false;

    emptySlot.item = {
      item: itemData,
      count: Math.min(count, itemData.maxStack),
      quality: quality || itemData.quality,
    };

    // 如果还有剩余物品，递归添加
    const remaining = count - (emptySlot.item.count || 0);
    if (remaining > 0) {
      return addItemToInventory(itemId, remaining, quality);
    }

    return true;
  };

  return {
    inventory,
    selectedSlot,
    initInventory,
    addItemToInventory,
  };
});
